package com.leetcode.matrix;

import com.leetcode.math.MaximumEvenSplit;

public class MinFallingPathSum {
    public static void main(String[] args) {
        int[][] matrix = {{2,1,3},{6,5,4},{7,8,9}};
        MinFallingPathSum minFallingPathSum = new MinFallingPathSum();
        System.out.println(minFallingPathSum.minFallingPathSum(matrix));
    }

    public int minFallingPathSum(int[][] matrix) {
        int res = Integer.MAX_VALUE;
        int r = matrix.length;
        int c = matrix[0].length;
        int[][] dp = new int[r][c];
        for (int j = 0; j < c; j++) {
            dp[0][j] = matrix[0][j];
        }
        for (int i = 1; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (j == 0) {
                    dp[i][j] = Math.min(dp[i-1][j], dp[i - 1][j+1]) + matrix[i][j];
                } else if (j == c - 1) {
                    dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1]) + matrix[i][j];
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i - 1][j - 1]),
                            dp[i - 1][j + 1]) + matrix[i][j];
                }
            }
        }
        for (int j = 0; j < c; j++) {
            res = Math.min(dp[r-1][j], res);
        }
        return res;
    }
}
